#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/24 19:07
# @Author  : 李中华
# @Email   : 1260429766@qq.com
# @File    : codecTools.py
from urllib import parse
import binascii
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_v1_5

'''编解码工具封装，两种编解码：1.url百年解码。2.RSA编解码'''

class urlCodecTool:
    '''URL编解码封装'''

    def __init__(self, string):
        self.string = string

    @property
    def urlEncode(self):
        return parse.quote(self.string)

    @property
    def urlDecode(self, ):
        return parse.unquote(self.string)


class CryptoTool:
    '''RSA编解码'''
    def __init__(self):
        try:
            key = RSA.generate(2048)
            encrypted_key = key.exportKey(pkcs=8)
            self.public_key = key.publickey().exportKey().decode('utf-8')
            self.private_key = encrypted_key.decode('utf-8')
            # print({'state': "success", 'message': {'public_key': self.public_key, 'private_key': self.private_key}})
        except Exception as err:
            print({'state': "fail", 'message': str(err)})

    def create_rsa_key(self):
        '''生成RSA秘钥对，现修改，构造函数代替此功能'''
        try:
            key = RSA.generate(2048)
            encrypted_key = key.exportKey(pkcs=8)

            public_key = key.publickey().exportKey().decode('utf-8')
            private_key = encrypted_key.decode('utf-8')

            return {'state': "success", 'message': {'public_key': public_key, 'private_key': private_key}}
        except Exception as err:
            return {'state': "fail", 'message': str(err)}

    def encrypt(self, plaintext):
        '''此前从文件中读取公钥，现修改，不从文件中去公钥调用私有RSA加密方法'''
        return self.__encrypt(self.public_key, plaintext)

    def decrypt(self, hex_data):
        '''此前从文件中读取私钥，现修改，不从文件中调用私有RSA解密方法'''
        return self.__decrypt(self.private_key, hex_data)

    def __encrypt(self, public_key, plaintext):
        '''RSA加密方法封装'''
        try:
            recipient_key = RSA.import_key(public_key)
            cipher_rsa = PKCS1_v1_5.new(recipient_key)

            en_data = cipher_rsa.encrypt(plaintext.encode('utf-8'))
            hex_data = binascii.hexlify(en_data).decode('utf-8')

            return {'state': "success", 'message': hex_data}
        except Exception as err:
            return {'state': 0, 'message': str(err)}

    def __decrypt(self, private_key, hex_data):
        '''RSA解密方法封装'''
        try:

            private_key = RSA.import_key(private_key)
            cipher_rsa = PKCS1_v1_5.new(private_key)

            en_data = binascii.unhexlify(hex_data.encode('utf-8'))
            data = cipher_rsa.decrypt(en_data, None).decode('utf-8')

            return {'state': "success", 'message': data}
        except Exception as err:
            return {'state': "fail", 'message': str(err)}


if __name__ == '__main__':
    # print(urlCODEC('%E5%92%8C').urlDecode)
    # print(urlCODEC('和').urlEncode)
    rsaTool = CryptoTool()
    print(rsaTool.encrypt('李中华'))
    print(rsaTool.decrypt(rsaTool.encrypt('李中华')['message']))

